<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
    
  
  <link href="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Web,JavaScript," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="事件流事件类型鼠标与滚轮事件页面坐标位置通过客户区坐标能够知道鼠标是在视口中什么位置发生的，而页面坐标通过事件对象的pageX 和pageY 属性，能告诉你事件是在页面中的什么位置发生的。这两个属性表示鼠标光标在页面中的位置，因此坐标是从页面本身而非视口的左边和顶边计算的。
12345var div = document.getElementById(&quot;myDiv&quot;);EventUtil.addH">
<meta property="og:type" content="article">
<meta property="og:title" content="《 JavaScript 高级程序设计》备忘-第十三章-4">
<meta property="og:url" content="http://codingme.xyz/2016/10/16/javascript-note-13-4/index.html">
<meta property="og:site_name" content="CodingMe">
<meta property="og:description" content="事件流事件类型鼠标与滚轮事件页面坐标位置通过客户区坐标能够知道鼠标是在视口中什么位置发生的，而页面坐标通过事件对象的pageX 和pageY 属性，能告诉你事件是在页面中的什么位置发生的。这两个属性表示鼠标光标在页面中的位置，因此坐标是从页面本身而非视口的左边和顶边计算的。
12345var div = document.getElementById(&quot;myDiv&quot;);EventUtil.addH">
<meta property="og:updated_time" content="2016-10-18T06:23:42.122Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《 JavaScript 高级程序设计》备忘-第十三章-4">
<meta name="twitter:description" content="事件流事件类型鼠标与滚轮事件页面坐标位置通过客户区坐标能够知道鼠标是在视口中什么位置发生的，而页面坐标通过事件对象的pageX 和pageY 属性，能告诉你事件是在页面中的什么位置发生的。这两个属性表示鼠标光标在页面中的位置，因此坐标是从页面本身而非视口的左边和顶边计算的。
12345var div = document.getElementById(&quot;myDiv&quot;);EventUtil.addH">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codingme.xyz/2016/10/16/javascript-note-13-4/"/>





  <title> 《 JavaScript 高级程序设计》备忘-第十三章-4 | CodingMe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">CodingMe</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://codingme.xyz/2016/10/16/javascript-note-13-4/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Huang SJ">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="CodingMe">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="CodingMe" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                《 JavaScript 高级程序设计》备忘-第十三章-4
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="事件流"><a href="#事件流" class="headerlink" title="事件流"></a>事件流</h1><h2 id="事件类型"><a href="#事件类型" class="headerlink" title="事件类型"></a>事件类型</h2><h3 id="鼠标与滚轮事件"><a href="#鼠标与滚轮事件" class="headerlink" title="鼠标与滚轮事件"></a>鼠标与滚轮事件</h3><h4 id="页面坐标位置"><a href="#页面坐标位置" class="headerlink" title="页面坐标位置"></a>页面坐标位置</h4><p>通过客户区坐标能够知道鼠标是在视口中什么位置发生的，<br>而页面坐标通过事件对象的pageX 和pageY 属性，能告诉你事件是在页面中的什么位置发生的。<br>这两个属性表示鼠标光标在页面中的位置，因此坐标是从页面本身而非视口的左边和顶边计算的。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> div = <span class="built_in">document</span>.getElementById(<span class="string">"myDiv"</span>);</div><div class="line">EventUtil.addHandler(div, <span class="string">"click"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    alert(<span class="string">"Page coordinates: "</span> + event.pageX + <span class="string">","</span> + event.pageY);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>在页面没有滚动的情况下，pageX 和pageY 的值与clientX 和clientY 的值相等。<br>IE8 及更早版本不支持事件对象上的页面坐标，不过使用客户区坐标和滚动信息可以计算出来。<br>这时候需要用到document.body(混杂模式)或document.documentElement(标准模式)中的scrollLeft 和scrollTop 属性。<br><a id="more"></a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> div = <span class="built_in">document</span>.getElementById(<span class="string">"myDiv"</span>);</div><div class="line">EventUtil.addHandler(div, <span class="string">"click"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    <span class="keyword">var</span> pageX = event.pageX,</div><div class="line">    pageY = event.pageY;</div><div class="line">    <span class="keyword">if</span> (pageX === <span class="literal">undefined</span>)&#123;</div><div class="line">        pageX = event.clientX + (<span class="built_in">document</span>.body.scrollLeft ||</div><div class="line">        <span class="built_in">document</span>.documentElement.scrollLeft);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span> (pageY === <span class="literal">undefined</span>)&#123;</div><div class="line">        pageY = event.clientY + (<span class="built_in">document</span>.body.scrollTop ||</div><div class="line">        <span class="built_in">document</span>.documentElement.scrollTop);</div><div class="line">    &#125;</div><div class="line">    alert(<span class="string">"Page coordinates: "</span> + pageX + <span class="string">","</span> + pageY);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<h4 id="屏幕坐标位置"><a href="#屏幕坐标位置" class="headerlink" title="屏幕坐标位置"></a>屏幕坐标位置</h4><p>鼠标事件发生时，不仅会有相对于浏览器窗口的位置，还有一个相对于整个电脑屏幕的位置。<br>而通过screenX 和screenY 属性就可以确定鼠标事件发生时鼠标指针相对于整个屏幕的坐标信息。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> div = <span class="built_in">document</span>.getElementById(<span class="string">"myDiv"</span>);</div><div class="line">EventUtil.addHandler(div, <span class="string">"click"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    alert(<span class="string">"Screen coordinates: "</span> + event.screenX + <span class="string">","</span> + event.screenY);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<h4 id="修改键"><a href="#修改键" class="headerlink" title="修改键"></a>修改键</h4><p>虽然鼠标事件主要是使用鼠标来触发的，但在按下鼠标时键盘上的某些键的状态也可以影响到所要采取的操作。<br>这些修改键就是Shift、Ctrl、Alt 和Meta(在Windows 键盘中是Windows 键，在苹果机中是Cmd 键)，它们经常被用来修改鼠标事件的行为。<br>DOM 为此规定了4 个属性，表示这些修改键的状态：shiftKey、ctrlKey、altKey 和metaKey。<br>这些属性中包含的都是布尔值，如果相应的键被按下了，则值为true，否则值为false。<br>当某个鼠标事件发生时，通过检测这几个属性就可以确定用户是否同时按下了其中的键。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> div = <span class="built_in">document</span>.getElementById(<span class="string">"myDiv"</span>);</div><div class="line">EventUtil.addHandler(div, <span class="string">"click"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">    event = EventUtil.getEvent(event);</div><div class="line">    <span class="keyword">var</span> keys = <span class="keyword">new</span> <span class="built_in">Array</span>();</div><div class="line">    <span class="keyword">if</span> (event.shiftKey)&#123;</div><div class="line">        keys.push(<span class="string">"shift"</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span> (event.ctrlKey)&#123;</div><div class="line">        keys.push(<span class="string">"ctrl"</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span> (event.altKey)&#123;</div><div class="line">        keys.push(<span class="string">"alt"</span>);</div><div class="line">    &#125;</div><div class="line">    <span class="keyword">if</span> (event.metaKey)&#123;</div><div class="line">        keys.push(<span class="string">"meta"</span>);</div><div class="line">    &#125;</div><div class="line">    alert(<span class="string">"Keys: "</span> + keys.join(<span class="string">","</span>));</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>IE9、Firefox、Safari、Chrome 和Opera 都支持这4 个键。IE8 及之前版本不支持metaKey 属性。</p>
<h4 id="相关元素"><a href="#相关元素" class="headerlink" title="相关元素"></a>相关元素</h4><p>在发生mouseover 和mouserout 事件时，还会涉及更多的元素。<br>这两个事件都会涉及把鼠标指针从一个元素的边界之内移动到另一个元素的边界之内。<br>对mouseover 事件而言，事件的主目标是获得光标的元素，而相关元素就是那个失去光标的元素。<br>类似地，对mouseout 事件而言，事件的主目标是失去光标的元素，而相关元素则是获得光标的元素。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;!DOCTYPE html&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">title</span>&gt;</span>Related Elements Example<span class="tag">&lt;/<span class="name">title</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></div><div class="line">    <span class="tag">&lt;<span class="name">body</span>&gt;</span></div><div class="line">        <span class="tag">&lt;<span class="name">div</span> <span class="attr">id</span>=<span class="string">"myDiv"</span> <span class="attr">style</span>=<span class="string">"background-color:red;height:100px;width:100px;"</span>&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></div></pre></td></tr></table></figure>
<p>如果鼠标指针一开始位于这个<code>&lt;div&gt;</code>元素上，然后移出了这个元素，那么就会在<code>&lt;div&gt;</code>元素上触发mouseout 事件，相关元素就是<code>&lt;body&gt;</code>元素。<br>与此同时，<code>&lt;body&gt;</code>元素上面会触发mouseover 事件，而相关元素变成了<code>&lt;div&gt;</code>。<br>DOM通过event 对象的relatedTarget 属性提供了相关元素的信息。<br>这个属性只对于mouseover和mouseout 事件才包含值；对于其他事件，这个属性的值是null。<br>IE8及之前版本不支持relatedTarget属性，但提供了保存着同样信息的不同属性。<br>在mouseover 事件触发时，IE 的fromElement 属性中保存了相关元素；<br>在mouseout 事件触发时，IE 的toElement 属性中保存着相关元素。(IE9 支持所有这些属性。)</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> EventUtil = &#123;</div><div class="line"><span class="comment">//省略了其他代码</span></div><div class="line">    getRelatedTarget: <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">        <span class="keyword">if</span> (event.relatedTarget)&#123;</div><div class="line">            <span class="keyword">return</span> event.relatedTarget;</div><div class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (event.toElement)&#123;</div><div class="line">            <span class="keyword">return</span> event.toElement;</div><div class="line">        &#125; <span class="keyword">else</span> <span class="keyword">if</span> (event.fromElement)&#123;</div><div class="line">            <span class="keyword">return</span> event.fromElement;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="keyword">return</span> <span class="literal">null</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"><span class="comment">//省略了其他代码</span></div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<h4 id="鼠标按钮"><a href="#鼠标按钮" class="headerlink" title="鼠标按钮"></a>鼠标按钮</h4><p>只有在主鼠标按钮被单击(或键盘回车键被按下)时才会触发click 事件，因此检测按钮的信息并不是必要的。<br>但对于mousedown 和mouseup 事件来说，则在其event 对象存在一个button 属性，表示按下或释放的按钮。<br>DOM的button 属性可能有如下3 个值：0 表示主鼠标按钮，1 表示中间的鼠标按钮(鼠标滚轮按钮)，2 表示次鼠标按钮。<br>IE8 及之前版本也提供了button 属性，但这个属性的值与DOM 的button 属性有很大差异。</p>
<ul>
<li>0：表示没有按下按钮。</li>
<li>1：表示按下了主鼠标按钮。</li>
<li>2：表示按下了次鼠标按钮。</li>
<li>3：表示同时按下了主、次鼠标按钮。</li>
<li>4：表示按下了中间的鼠标按钮。</li>
<li>5：表示同时按下了主鼠标按钮和中间的鼠标按钮。</li>
<li>6：表示同时按下了次鼠标按钮和中间的鼠标按钮。</li>
<li>7：表示同时按下了三个鼠标按钮。</li>
</ul>
<p>DOM 模型下的button 属性比IE 模型下的button 属性更简单也更为实用，因为同时按下多个鼠标按钮的情形十分罕见。<br>最常见的做法就是将IE 模型规范化为DOM 方式，毕竟除IE8 及更早版本之外的其他浏览器都原生支持DOM 模型。<br>而对主、中、次按钮的映射并不困难，只要将IE 的其他选项分别转换成如同按下这三个按键中的一个即可(同时将主按钮作为优先选取的对象)。<br>换句话说，IE 中返回的5 和7 会被转换成DOM 模型中的0。</p>
<p>由于单独使用能力检测无法确定差异(两种模型有同名的button 属性)，因此必须另辟蹊径。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> EventUtil = &#123;</div><div class="line"><span class="comment">//省略了其他代码</span></div><div class="line">    getButton: <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">        <span class="keyword">if</span> (<span class="built_in">document</span>.implementation.hasFeature(<span class="string">"MouseEvents"</span>, <span class="string">"2.0"</span>))&#123;</div><div class="line">            <span class="keyword">return</span> event.button;</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="keyword">switch</span>(event.button)&#123;</div><div class="line">                <span class="keyword">case</span> <span class="number">0</span>:</div><div class="line">                <span class="keyword">case</span> <span class="number">1</span>:</div><div class="line">                <span class="keyword">case</span> <span class="number">3</span>:</div><div class="line">                <span class="keyword">case</span> <span class="number">5</span>:</div><div class="line">                <span class="keyword">case</span> <span class="number">7</span>:</div><div class="line">                    <span class="keyword">return</span> <span class="number">0</span>;</div><div class="line">                <span class="keyword">case</span> <span class="number">2</span>:</div><div class="line">                <span class="keyword">case</span> <span class="number">6</span>:</div><div class="line">                    <span class="keyword">return</span> <span class="number">2</span>;</div><div class="line">                <span class="keyword">case</span> <span class="number">4</span>:</div><div class="line">                    <span class="keyword">return</span> <span class="number">1</span>;</div><div class="line">            &#125;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line"><span class="comment">//省略了其他代码</span></div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<p>通过检测”MouseEvents”这个特性，就可以确定event 对象中存在的button 属性中是否包含正确的值。<br>如果测试失败，说明是IE，就必须对相应的值进行规范化。</p>
<h4 id="更多的事件信息"><a href="#更多的事件信息" class="headerlink" title="更多的事件信息"></a>更多的事件信息</h4><p>event 对象中还提供了detail 属性，用于给出有关事件的更多信息。<br>对于鼠标事件来说，detail 中包含了一个数值，表示在给定位置上发生了多少次单击。<br>在同一个元素上相继地发生一次mousedown 和一次mouseup 事件算作一次单击。<br>detail 属性从1 开始计数，每次单击发生后都会递增。<br>如果鼠标在mousedown 和mouseup 之间移动了位置，则detail 会被重置为0。<br>IE 也通过下列属性为鼠标事件提供了更多信息。</p>
<ul>
<li>altLeft：布尔值，表示是否按下了Alt 键。如果altLeft 的值为true，则altKey 的值也为true。</li>
<li>ctrlLeft：布尔值，表示是否按下了Ctrl 键。如果ctrlLeft 的值为true，则ctrlKey 的值也为true。</li>
<li>offsetX：光标相对于目标元素边界的x 坐标。</li>
<li>offsetY：光标相对于目标元素边界的y 坐标。</li>
<li>shiftLeft：布尔值，表示是否按下了Shift 键。如果shiftLeft 的值为true，则shiftKey的值也为true。</li>
</ul>
<h4 id="鼠标滚轮事件"><a href="#鼠标滚轮事件" class="headerlink" title="鼠标滚轮事件"></a>鼠标滚轮事件</h4><p>IE 6.0 首先实现了mousewheel 事件。此后，Opera、Chrome 和Safari 也都实现了这个事件。<br>当用户通过鼠标滚轮与页面交互、在垂直方向上滚动页面时(无论向上还是向下)，就会触发mousewheel事件。<br>这个事件可以在任何元素上面触发，最终会冒泡到document(IE8)或window(IE9、Opera、Chrome 及Safari)对象。<br>与mousewheel 事件对应的event 对象除包含鼠标事件的所有标准信息外，还包含一个特殊的wheelDelta 属性。<br>当用户向前滚动鼠标滚轮时，wheelDelta 是120 的倍数；当用户向后滚动鼠标滚轮时，wheelDelta 是-120 的倍数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"mousewheel"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">event = EventUtil.getEvent(event);</div><div class="line">alert(event.wheelDelta);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>在Opera 9.5 之前的版本中，wheelDelta 值的正负号是颠倒的。</p>
<p>由于mousewheel 事件非常流行，而且所有浏览器都支持它，所以HTML 5 也加入了该事件。</p>
<p>Firefox 支持一个名为DOMMouseScroll 的类似事件，也是在鼠标滚轮滚动时触发。<br>与mousewheel事件一样，DOMMouseScroll 也被视为鼠标事件，因而包含与鼠标事件有关的所有属性。<br>而有关鼠标滚轮的信息则保存在detail 属性中，当向前滚动鼠标滚轮时，这个属性的值是-3 的倍数，当向后滚动鼠标滚轮时，这个属性的值是3 的倍数。</p>
<p>可以将DOMMouseScroll 事件添加到页面中的任何元素，而且该事件会冒泡到window 对象。<br>因此，可以像下面这样针对这个事件来添加事件处理程序。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">EventUtil.addHandler(<span class="built_in">window</span>, <span class="string">"DOMMouseScroll"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">event = EventUtil.getEvent(event);</div><div class="line">alert(event.detail);</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>跨浏览器环境下的解决方案:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> EventUtil = &#123;</div><div class="line">    <span class="comment">//省略了其他代码</span></div><div class="line">    getWheelDelta: <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">        <span class="keyword">if</span> (event.wheelDelta)&#123;</div><div class="line">            <span class="keyword">return</span> (client.engine.opera &amp;&amp; client.engine.opera &lt; <span class="number">9.5</span> ?</div><div class="line">            -event.wheelDelta : event.wheelDelta);</div><div class="line">        &#125; <span class="keyword">else</span> &#123;</div><div class="line">            <span class="keyword">return</span> -event.detail * <span class="number">40</span>;</div><div class="line">        &#125;</div><div class="line">    &#125;,</div><div class="line">    <span class="comment">//省略了其他代码</span></div><div class="line">&#125;;</div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">    <span class="function"><span class="keyword">function</span> <span class="title">handleMouseWheel</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">        event = EventUtil.getEvent(event);</div><div class="line">        <span class="keyword">var</span> delta = EventUtil.getWheelDelta(event);</div><div class="line">        alert(delta);</div><div class="line">    &#125;</div><div class="line">    EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"mousewheel"</span>, handleMouseWheel);</div><div class="line">    EventUtil.addHandler(<span class="built_in">document</span>, <span class="string">"DOMMouseScroll"</span>, handleMouseWheel);</div><div class="line">&#125;)();</div></pre></td></tr></table></figure>
<p>相关代码放在了一个私有作用域中，从而不会让新定义的函数干扰全局作用域。<br>这里定义的handleMouseWheel()函数可以用作两个事件的处理程序(如果指定的事件不存在，则为该事件指定处理程序的代码就会静默地失败)。</p>
<h4 id="触摸设备"><a href="#触摸设备" class="headerlink" title="触摸设备"></a>触摸设备</h4><ul>
<li>不支持dblclick 事件。双击浏览器窗口会放大画面，而且没有办法改变该行为。</li>
<li>轻击可单击元素会触发mousemove 事件。如果此操作会导致内容变化，将不再有其他事件发生；<br>  如果屏幕没有因此变化，那么会依次发生mousedown、mouseup 和click 事件。轻击不可单击的元素不会触发任何事件。可单击的元素是指那些单击可产生默认操作的元素(如链接)，或者那些已经被指定了onclick 事件处理程序的元素。</li>
<li>mousemove 事件也会触发mouseover 和mouseout 事件。</li>
<li>两个手指放在屏幕上且页面随手指移动而滚动时会触发mousewheel 和scroll 事件。</li>
</ul>
<h4 id="无障碍性问题"><a href="#无障碍性问题" class="headerlink" title="无障碍性问题"></a>无障碍性问题</h4><p>可以通过键盘上的回车键来触发click 事件，但其他鼠标事件却无法通过键盘来触发。<br>为此，我们不建议使用click 之外的其他鼠标事件来展示功能或引发代码执行。因为这样会给盲人或视障用户造成极大不便。</p>
<ul>
<li>使用click 事件执行代码。有人指出通过onmousedown 执行代码会让人觉得速度更快，对视力正常的人来说这是没错的。<br>  但是，在屏幕阅读器中，由于无法触发mousedown 事件，结果就会造成代码无法执行。</li>
<li>不要使用onmouseover 向用户显示新的选项。原因同上，屏幕阅读器无法触发这个事件。如果确实非要通过这种方式来显示新选项，可以考虑添加显示相同信息的键盘快捷方式。</li>
<li>不要使用dblclick 执行重要的操作。键盘无法触发这个事件。</li>
</ul>
<h3 id="键盘与文本事件"><a href="#键盘与文本事件" class="headerlink" title="键盘与文本事件"></a>键盘与文本事件</h3><p>“DOM2 级事件”最初规定了键盘事件，但在最终定稿之前又删除了相应的内容。<br>结果，对键盘事件的支持主要遵循的是DOM0 级。<br>“DOM3 级事件”为键盘事件制定了规范，IE9 率先完全实现了该规范。</p>
<ul>
<li>keydown：当用户按下键盘上的任意键时触发，而且如果按住不放的话，会重复触发此事件。</li>
<li>keypress：当用户按下键盘上的字符键时触发，而且如果按住不放的话，会重复触发此事件。<br>  按下Esc 键也会触发这个事件。Safari 3.1 之前的版本也会在用户按下非字符键时触发keypress事件。</li>
<li>keyup：当用户释放键盘上的键时触发。</li>
</ul>
<p>虽然所有元素都支持以上3 个事件，但只有在用户通过文本框输入文本时才最常用到。<br>只有一个文本事件：textInput。这个事件是对keypress 的补充，用意是在将文本显示给用户之前更容易拦截文本。<br>在文本插入文本框之前会触发textInput 事件。</p>
<p>在用户按了一下键盘上的字符键时，首先会触发keydown 事件，然后紧跟着是keypress 事件，最后会触发keyup 事件。<br>其中，keydown 和keypress 都是在文本框发生变化之前被触发的；<br>而keyup事件则是在文本框已经发生变化之后被触发的。<br>如果用户按下的是一个非字符键，那么首先会触发keydown 事件，然后就是keyup 事件。<br>如果按住这个非字符键不放，那么就会一直重复触发keydown 事件，直到用户松开这个键，此时会触发keyup事件。<br>键盘事件与鼠标事件一样，都支持相同的修改键。<br>而且，键盘事件的事件对象中也有shiftKey、ctrlKey、altKey 和metaKey 属性。IE 不支持metaKey。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Web/" rel="tag"># Web</a>
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/16/javascript-note-13-3/" rel="next" title="《 JavaScript 高级程序设计》备忘-第十三章-3">
                <i class="fa fa-chevron-left"></i> 《 JavaScript 高级程序设计》备忘-第十三章-3
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/16/javascript-note-13-5/" rel="prev" title="《 JavaScript 高级程序设计》备忘-第十三章-5">
                《 JavaScript 高级程序设计》备忘-第十三章-5 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="Huang SJ" />
          <p class="site-author-name" itemprop="name">Huang SJ</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">75</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hsj1992" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/hsj9527" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1694147905" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.freecodecamp.cn/hsj1992" target="_blank" title="FreeCodeCamp">
                  
                    <i class="fa fa-fw fa-fire"></i>
                  
                  FreeCodeCamp
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://codepen.io/hsj1992/" target="_blank" title="codepen">
                  
                    <i class="fa fa-fw fa-codepen"></i>
                  
                  codepen
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://hsj1992.oschina.io/" target="_blank" title="码云镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  码云镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.coding.me/" target="_blank" title="coding镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  coding镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.github.io/" target="_blank" title="github镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  github镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://codingme-6dd8a.firebaseapp.com" target="_blank" title="Firebase镜像">
                  
                    <i class="fa fa-fw fa-google"></i>
                  
                  Firebase镜像
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#事件流"><span class="nav-number">1.</span> <span class="nav-text">事件流</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#事件类型"><span class="nav-number">1.1.</span> <span class="nav-text">事件类型</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#鼠标与滚轮事件"><span class="nav-number">1.1.1.</span> <span class="nav-text">鼠标与滚轮事件</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#页面坐标位置"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">页面坐标位置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#屏幕坐标位置"><span class="nav-number">1.1.1.2.</span> <span class="nav-text">屏幕坐标位置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#修改键"><span class="nav-number">1.1.1.3.</span> <span class="nav-text">修改键</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#相关元素"><span class="nav-number">1.1.1.4.</span> <span class="nav-text">相关元素</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#鼠标按钮"><span class="nav-number">1.1.1.5.</span> <span class="nav-text">鼠标按钮</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#更多的事件信息"><span class="nav-number">1.1.1.6.</span> <span class="nav-text">更多的事件信息</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#鼠标滚轮事件"><span class="nav-number">1.1.1.7.</span> <span class="nav-text">鼠标滚轮事件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#触摸设备"><span class="nav-number">1.1.1.8.</span> <span class="nav-text">触摸设备</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#无障碍性问题"><span class="nav-number">1.1.1.9.</span> <span class="nav-text">无障碍性问题</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#键盘与文本事件"><span class="nav-number">1.1.2.</span> <span class="nav-text">键盘与文本事件</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Huang SJ</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
